package ast;

import java.util.ArrayList;

import ast.Statement.StatementType;

public class StructuralStatement extends Statement {
	// StructualStatement
	// IF_STMT, WHILE_STMT, FOR_STMT
	
	// IF和WHILE都只有一个（填Expression类），FOR语句有三个（第三个是Expression类, 如果是空的话填上VOID_STMT）
	public ArrayList<AstItem> controlConditions = new ArrayList<AstItem>();
	// Statement类
	public AstItem state;

	public AstItem stateElse;
	
	public String toString() {
		String result = "";
		if (type == StatementType.IF_STMT) {
			assert controlConditions.size() == 1;
			result += "if (" + controlConditions.get(0).toString() + ")" + " " + state.toString();
			if (stateElse != null) {
				result += "else " + stateElse.toString();
			}
		}
		else if (type == StatementType.WHILE_STMT) {
			assert controlConditions.size() == 1;
			result += "while (" + controlConditions.get(0).toString() + ")" + " " + state.toString();
		}
		else {
			assert type == StatementType.FOR_STMT;
			assert controlConditions.size() == 3;
			result += "for (";
			for (int i = 0;i < controlConditions.size();i++) {
				if (i == 2) {
					if (controlConditions.get(i) != null) {
						String stmtString = controlConditions.get(2).toString();
						// 去掉分号
						result += stmtString.substring(0, stmtString.length() - 1);
					}
				} else {
					if (controlConditions.get(i) != null) {
						String stmtString = controlConditions.get(i).toString();
						result += stmtString;
						if (i == 1) result += ";";
					} else {
						result += ";";
					}
				}
			}
			result += ") " + state.toString(); 
		}
		return result;
	}
	
	public void preprocess(AstItem father) {
		for (AstItem x : controlConditions) { 
			x.preprocess(this);
		}
		state.preprocess(this);
		if (stateElse != null) stateElse.preprocess(this);
	}

	@Override
	public String toJsonString() {
		String json = "{";
		json += "\"Type\": \"Statement-" + type.toString() + "\",";
		json += "\"ControlConditions\": [";
		for (AstItem astItem: controlConditions) {
			if (astItem != null) {
				json += astItem.toJsonString();
			}
			json += ",";
		}
		json += "],";
		json += "\"State\":" + state.toJsonString() + ",";
		json += "\"StateElse\":" + (stateElse != null ? stateElse.toJsonString() : "\"\"");
		json += "}";
		return json;
	}
}
